package org.jimmy.tang.calendar;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Scanner;

/**
 * @author jimmy
 * 
 */
public class CalendarDemo {
    static Scanner cin = new Scanner(System.in);

    public static void main(String[] args) {
        test();
    }

    public static void test() {
        Locale.setDefault(Locale.US);// 设置为美国地区
        System.out.print("Please input the year and month(like 1999 9):");
        int year = cin.nextInt();
        int month = cin.nextInt();
        GregorianCalendar day = new GregorianCalendar();// 从公元 4 年 3 月 1 日之后是准确的

        // 将day设置为该月的第一天
        day.set(Calendar.YEAR, year);
        day.set(Calendar.MONTH, month - 1);
        day.set(Calendar.DAY_OF_MONTH, 1);

        int weekday = day.get(Calendar.DAY_OF_WEEK);
        int firstDayOfWeek = day.getFirstDayOfWeek();

        int indent = 0;
        while (weekday != firstDayOfWeek) {
            indent++;
            day.add(Calendar.DAY_OF_MONTH, -1);
            weekday = day.get(Calendar.DAY_OF_WEEK);
        }

        String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
        do {
            System.out.printf("%4s", weekdayNames[weekday]);
            day.add(Calendar.DAY_OF_MONTH, 1);
            weekday = day.get(Calendar.DAY_OF_WEEK);
        } while (weekday != firstDayOfWeek);
        System.out.println();

        for (int i = 0; i < indent; i++) {
            System.out.print("    ");
        }
        day.set(Calendar.DAY_OF_MONTH, 1);

        do {
            int d = day.get(Calendar.DAY_OF_MONTH);
            System.out.printf("%4s", d);

            day.add(Calendar.DAY_OF_MONTH, 1);
            weekday = day.get(Calendar.DAY_OF_WEEK);

            if (weekday == firstDayOfWeek) {
                System.out.println();
            }
        } while ((month - 1) == day.get(Calendar.MONTH));

        if (weekday != firstDayOfWeek) {
            System.out.println();
        }
    }
}
